package service

import (
	"errors"
	"fmt"
	"im/database"
	"im/model"
	"im/util"
	"math/rand"
	"time"
)

type UserService struct {
	util.Util
}

func (s *UserService)Register(mobile,plainpwd,nickname,avatar,sex string)(user model.User,err error) {

	tmp := model.User{}
	//检测手机号是否存在
	_,err = database.DbCone.Where("mobile =? ",mobile).Get(&tmp)
	if nil != err {
		return tmp,err
	}
	//如果存在返回已注册
	if tmp.Id > 0 {
		return tmp,errors.New("该手机号已被注册")
	}
	//不存在插入数据库
	tmp.Mobile   = mobile
	tmp.Nickname = nickname
	tmp.Avatar   = avatar
	tmp.Sex      = sex
	tmp.Salt     = fmt.Sprintf("%06d",rand.Int31n(10000))
	tmp.Passwd   = s.MakePasswd(plainpwd,tmp.Salt)
	tmp.Createat = time.Now()
	tmp.Token    = s.MD5Encode(fmt.Sprintf("%08d",rand.Int31()))
	_ , err = database.DbCone.InsertOne(&tmp)
	if nil != err {
		return tmp,err
	}
	//返回注册信息
	return tmp,nil
}

func (s *UserService) UserLogin(mobile, password string) (user model.User, err error)  {
	//检测手机号是否存在
	var tmp model.User
	database.DbCone.Where("mobile = ?",mobile).Get(&tmp)
	//等于0是因为int类型默认为0，未查到用户的情况
	if tmp.Id == 0 {
		return tmp,errors.New("用户不存在")
	}
	//判断密码是否一致
	if !s.ValidatePasswd(password,tmp.Salt,tmp.Passwd) {
		return tmp,errors.New("密码错误")
	}
	//为了安全刷新token
	token := s.MD5Encode(fmt.Sprintf("%d",time.Now().Unix()))
	tmp.Token = token
	database.DbCone.Id(tmp.Id).Cols("token").Update(tmp)
	return tmp,nil
}

/**
	获取token
 */
func (s *UserService) GetToken(userId int64,is_data bool) interface{} {
	var tmp model.User
	database.DbCone.ID(userId).Get(&tmp);
	if tmp.Id == 0 {
		return ""
	}
	if is_data{
		return tmp;
	}
	return tmp.Token
}
